﻿using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using WebApi.Core.IRepository.Base;
using WebApi.Core.Model.ResponseModels;
using WebApi.Core.Repository.SqlSugar; 

namespace WebApi.Core.Repository.Base
{
    public class BaseRepository<TEntity> :IBaseRepository<TEntity> where TEntity : class, new()
    {
        private readonly ILogger<BaseRepository<TEntity>> _logger;
        protected readonly ISqlSugarClient _db;
         
        public BaseRepository(ILogger<BaseRepository<TEntity>> logger) 
        {
            _logger = logger;
            _db = DbContext.Db;
        }

        /// <summary>
        /// 插入实体
        /// </summary>
        public async Task<int> InsertAsync(TEntity model)
        {
            //return await _db.Insertable(model).ExecuteCommandAsync() > 0; 
            return await _db.Insertable(model).ExecuteReturnIdentityAsync(); 
        }

        /// <summary>
        /// 批量插入（高性能）
        /// </summary>
        public async Task<List<int>> InsertBatchAsync(List<TEntity> entities)
        { 
            return await _db.Insertable(entities).ExecuteReturnPkListAsync<int>();
        }

        /// <summary>
        /// 更新指定字段（防全表更新）
        /// </summary>
        public async Task<bool> UpdateAsync(TEntity entity)
        { 
            return await _db.Updateable(entity).ExecuteCommandHasChangeAsync();
        }

        public async Task<bool> UpdateAsync(TEntity entity, Expression<Func<TEntity, bool>> where, bool ignoreNull = true)
        {
            if (entity == null)
                return false;

            var update = _db.Updateable(entity).Where(where);
            
            if (ignoreNull)
                update.IgnoreNullColumns();

            return await update.ExecuteCommandHasChangeAsync();
        }

        /// <summary>
        /// 更新指定字段（防全表更新）
        /// </summary>
        public async Task<bool> UpdateAsync(TEntity entity, Expression<Func<TEntity, Object>>? columns = null, Expression<Func<TEntity, bool>>? where = null, bool ignoreNull = true)
        {
            if (entity == null)
                return false;

            var update = _db.Updateable(entity);

            if (columns != null)
                update.UpdateColumns(columns);

            if (where != null)
                update.Where(where);

            if (ignoreNull)
                update.IgnoreNullColumns();

            return await update.ExecuteCommandHasChangeAsync();
        }

        /// <summary>
        /// 删除指定ID的数据
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        public async Task<bool> DeleteByIdAsync(object id)
        {
            return await _db.Deleteable<TEntity>().In(id).ExecuteCommandHasChangeAsync();
        }

        /// <summary>
        /// 根据主键删除（防止误删全表）
        /// </summary>
        public async Task<bool> DeleteByIdsAsync(object[] ids)
        {
            if (ids == null || ids.Length == 0)
                throw new ArgumentException("删除ID不能为空");

            var del = _db.Deleteable<TEntity>().In(ids);
            string generatedSql = del.ToSqlString();

            _logger.LogInformation("DeleteSQL:{sql};Parameters:{pars}", generatedSql, string.Join(',', ids));

            return await del.ExecuteCommandAsync() > 0;
        }


        public async Task<TEntity> QueryById(object objId)
        { 
            return await _db.Queryable<TEntity>().In(objId).SingleAsync();
        }
        public async Task<TEntity> QueryAsync(Expression<Func<TEntity, bool>> where)
        {
            return await _db.Queryable<TEntity>().WhereIF(where != null, where).FirstAsync();
        }

        public async Task<List<TEntity>> QueryAsync(Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, object>> orderBy, bool isAsc = true)
        {
            return await _db.Queryable<TEntity>()
                .WhereIF(where != null, where)
                .OrderByIF(orderBy != null, orderBy, isAsc ? OrderByType.Asc : OrderByType.Desc).ToListAsync();

        }

        ///// <summary>
        ///// 按照特定列查询数据列表 
        ///// </summary>
        ///// <typeparam name="TResult"></typeparam>
        ///// <param name="expression"></param>
        ///// <returns></returns>
        //public async Task<List<TResult>> QueryAsync<TResult>(Expression<Func<TEntity, TResult>> expression)
        //{
        //    return await _db.Queryable<TEntity>().Select(expression).ToListAsync();
        //}

        ///// <summary>
        ///// 按照特定列查询数据列表带条件排序 
        ///// </summary>
        ///// <typeparam name="TResult"></typeparam>
        ///// <param name="whereExpression">过滤条件</param>
        ///// <param name="expression">查询实体条件</param>
        ///// <param name="orderByExpression">排序条件</param>
        ///// <returns></returns>
        //public async Task<List<TResult>> QueryAsync<TResult>(Expression<Func<TEntity, TResult>> expression, Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderByExpression)
        //{
        //    return await _db.Queryable<TEntity>().OrderByIF(orderByExpression != null, orderByExpression).WhereIF(whereExpression != null, whereExpression).Select(expression).ToListAsync();
        //}

        ///// <summary>
        ///// 查询列表
        ///// </summary>
        //public async Task<List<TEntity>> QueryAsync(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderByExpression, bool isAsc = true)
        //{
        //    var query = _db.Queryable<TEntity>()
        //        .WhereIF(whereExpression != null, whereExpression)
        //        .OrderByIF(orderByExpression != null, orderByExpression, isAsc? OrderByType.Asc : OrderByType.Desc);

        //    return await query.ToListAsync(); 
        //}

        /// <summary>
        /// 分页查询
        /// </summary> 
        public async Task<PageResult<TEntity>> QueryPageAsync(Expression<Func<TEntity, bool>> where, int pageIndex, int pageSize, Expression<Func<TEntity, object>> orderBy, bool isAsc = true)
        {
            // 处理分页默认值
            pageIndex = pageIndex < 1 ? 1 : pageIndex;
            pageSize = pageSize < 1 ? 20 : pageSize;

            var query = _db.Queryable<TEntity>()
                .WhereIF(where != null, where)
                .OrderByIF(orderBy != null, orderBy, isAsc ? OrderByType.Asc : OrderByType.Desc);

            RefAsync<int> totalCount = 0;
            var list = await query.ToPageListAsync(pageIndex, pageSize, totalCount);

            return new PageResult<TEntity>(pageIndex, pageSize, totalCount, list);
        }


        /// <summary>
        /// 是否存在
        /// </summary>
        public async Task<bool> ExistAsync(Expression<Func<TEntity, bool>> where)
        {
            return await _db.Queryable<TEntity>().Where(where).AnyAsync();
        }

        /// <summary>
        /// 获取数量
        /// </summary>
        public async Task<int> CountAsync(Expression<Func<TEntity, bool>>? where = null)
        {
            var query = _db.Queryable<TEntity>()
                .WhereIF(where != null, where); 
            return await query.CountAsync();
        }

    }
}
